//
//  LEPageViewController.m
//  CreditAddressBookEE
//
//  Created by LE on 16/2/16.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "LEPageViewController.h"

@interface LEPageViewController ()<UIPageViewControllerDelegate,
UIPageViewControllerDataSource, UIScrollViewDelegate>

@property(nonatomic, copy) LEControllerChanged block;

@end

@implementation LEPageViewController {
    UIPageViewController *_pageController;
    NSMutableDictionary *_viewControllers;
    NSUInteger _lastIndex;
    BOOL _disableDragging;
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self moveToPage:selectedIndex];
}

- (instancetype)initWithControllers:(NSArray *)controllers controllerChanged:(LEControllerChanged)controllerChanged {
    if (self = [super init]) {
        self.block = [controllerChanged copy];
        self.controllers = controllers;
        [self initContent];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupFirstController];
    [self addConstraints];
}

- (void)initContent {
    _pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    _pageController.delegate = self;
    _pageController.dataSource = self;
    
//    for (UIView *v in pageController.view.subviews) {
//        if ([v isKindOfClass:[UIScrollView class]]) {
//            ((UIScrollView *)v).delegate = self;
//        }
//    }
    [self addChildViewController:_pageController];
    [_pageController didMoveToParentViewController:self];
    
    _viewControllers = [[NSMutableDictionary alloc] init];
}

- (void)setupFirstController {
    [self.view addSubview:_pageController.view];
    id viewController = self.controllers[_selectedIndex];
    [_viewControllers setObject:viewController forKey:[NSNumber numberWithInteger:_selectedIndex]];
    
    [_pageController setViewControllers:@[viewController] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:^(BOOL finished) {
        
    }];
}

- (void)addConstraints {
    [_pageController.view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    UIView *pageControllerView = _pageController.view;
    [pageControllerView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
}

- (void)moveToPage:(NSUInteger)selectedIndex {
    UIViewController *viewController = [_viewControllers objectForKey:[NSNumber numberWithInteger:selectedIndex]];
    
    if (!viewController) {
        viewController = self.controllers[selectedIndex];
        [_viewControllers setObject:viewController forKey:[NSNumber numberWithInteger:selectedIndex]];
    }
    
    UIPageViewControllerNavigationDirection animateDirection =
    selectedIndex > _lastIndex ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    
    __unsafe_unretained typeof(self) weakSelf = self;
    _disableDragging = YES;
    _pageController.view.userInteractionEnabled = NO;
    [_pageController setViewControllers:@[viewController] direction:animateDirection
     animated:NO completion:^(BOOL finished) {
         weakSelf->_disableDragging = NO;
         weakSelf->_pageController.view.userInteractionEnabled = YES;
         weakSelf->_lastIndex = selectedIndex;
     }];
}

#pragma mark - PageViewController Delegate
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (!completed)
        return;
    
    id currentView = [pageViewController.viewControllers objectAtIndex:0];
    
    NSNumber *key = (NSNumber *)[_viewControllers allKeysForObject:currentView][0];
    _selectedIndex = [key integerValue];
    _lastIndex = _selectedIndex;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    NSInteger index = [self.controllers indexOfObject:viewController];
    _selectedIndex = index;
    if (self.block) {
        self.block(index);
    }
    
    if (index++ < self.controllers.count - 1) {
        UIViewController *nextViewController = [_viewControllers objectForKey:[NSNumber numberWithInteger:index]];
        
        if (!nextViewController) {
            nextViewController = self.controllers[index];
            [_viewControllers setObject:nextViewController forKey:[NSNumber numberWithInteger:index]];
        }
        return nextViewController;
    }
    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    
    NSInteger index = [self.controllers indexOfObject:viewController];
    _selectedIndex = index;
    if (self.block) {
        self.block(index);
    }
    
    if (index-- > 0) {
        UIViewController *nextViewController = [_viewControllers objectForKey:[NSNumber numberWithInteger:index]];
        
        if (!nextViewController) {
            nextViewController = self.controllers[index];
            [_viewControllers setObject:nextViewController forKey:[NSNumber numberWithInteger:index]];
        }
        return nextViewController;
    }
    return nil;
}
@end
